package com.flycms.modules.system.controller;

import java.util.List;
import java.util.Set;

import com.flycms.common.constant.Constants;
import com.flycms.common.utils.ServletUtils;
import com.flycms.framework.security.LoginAdmin;
import com.flycms.framework.security.LoginBody;
import com.flycms.framework.security.service.SysLoginService;
import com.flycms.framework.security.service.SysPermissionService;
import com.flycms.framework.security.service.TokenService;
import com.flycms.framework.web.domain.AjaxResult;
import com.flycms.modules.system.domain.FlyAdmin;
import com.flycms.modules.system.domain.FlyMenu;
import com.flycms.modules.system.service.IFlyMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * 登录验证
 * 
 * @author kaifei sun
 */
@RestController
public class FlyLoginController
{
    @Autowired
    private SysLoginService loginService;

    @Autowired
    private IFlyMenuService menuService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private TokenService tokenService;

    /**
     * 登录方法
     *
     * @return 结果
     */
    @PostMapping("/system/login")
    public AjaxResult login(@RequestBody LoginBody loginBody)
    {
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
                loginBody.getUuid());
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }

    /**
     * 获取用户信息
     * 
     * @return 用户信息
     */
    @GetMapping("/system/getInfo")
    public AjaxResult getInfo()
    {
        LoginAdmin loginAdmin = tokenService.getLoginAdmin(ServletUtils.getRequest());
        FlyAdmin user = loginAdmin.getAdmin();
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("user", user);
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);
        return ajax;
    }

    /**
     * 获取路由信息
     * 
     * @return 路由信息
     */
    @GetMapping("/system/getRouters")
    public AjaxResult getRouters()
    {
        LoginAdmin loginAdmin = tokenService.getLoginAdmin(ServletUtils.getRequest());
        // 用户信息
        FlyAdmin user = loginAdmin.getAdmin();
        List<FlyMenu> menus = menuService.selectMenuTreeByAdminId(user.getAdminId());
        return AjaxResult.success(menuService.buildMenus(menus));
    }
}
